<template>
  <div
    style="width: 100%; height: 100%; overflow-x: hidden; overflow-y: hidden"
  >
    <div class="list-card">
      <div class="top-nav">
        <div>
          <el-button
            @click="toPageSystem"
            size="mini"
            :icon="ArrowLeftBold"
            title="返回"
          ></el-button>
          <el-button
            @click="onLoad"
            size="mini"
            :icon="Refresh"
            title="刷新"
          ></el-button>
          <el-button
            @click="showAdd"
            size="mini"
            :icon="Plus"
            title="新增"
            v-if="usertype === 'ADMIN'"
          ></el-button>
        </div>
        <div style="display: flex; align-items: center">
          <div style="display: inline-block; padding-right: 15px">
            <el-avatar
              :size="28"
              :src="circleUrl"
              :title="username"
            ></el-avatar>
          </div>
          <div style="display: inline-block; padding-right: 10px">
            <el-dropdown>
              <span class="el-dropdown-link">
                {{ username }}
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="toPageSystem"
                    >文件系统</el-dropdown-item
                  >
                  <el-dropdown-item divided @click="logout"
                    >退出系统</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
      <el-table
        ref="singleTable"
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column type="index" label="ID" width="50" />
        <el-table-column property="name" label="User" width="100" />
        <el-table-column property="type" label="Type" width="100" />
        <el-table-column property="access.list" label="List" width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.access.list"
              @change="
                changeUserAccess(scope.row.id, 'list', scope.row.access.list)
              "
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column property="access.read" label="Read" width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.access.read"
              @change="
                changeUserAccess(scope.row.id, 'read', scope.row.access.read)
              "
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column property="access.write" label="Write" width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.access.write"
              @change="
                changeUserAccess(scope.row.id, 'write', scope.row.access.write)
              "
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column property="access.rename" label="Rename" width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.access.rename"
              @change="
                changeUserAccess(
                  scope.row.id,
                  'rename',
                  scope.row.access.rename
                )
              "
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column property="access.create" label="Create" width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.access.create"
              @change="
                changeUserAccess(
                  scope.row.id,
                  'create',
                  scope.row.access.create
                )
              "
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column property="access.create" label="Remove" width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.access.remove"
              @change="
                changeUserAccess(
                  scope.row.id,
                  'remove',
                  scope.row.access.remove
                )
              "
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="Operation" width="125">
          <template #default="scope">
            <el-button
              size="mini"
              type="primary"
              title="编辑"
              @click="handleEdit(scope.$index, scope.row)"
              :icon="Edit"
            ></el-button>
            <el-button
              v-if="usertype === 'ADMIN'"
              size="mini"
              type="danger"
              title="删除"
              @click="handleDelete(scope.$index, scope.row)"
              :icon="Delete"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog v-model="outerVisible" title="新增用户">
      <template #default>
        <el-form
          ref="ruleForm"
          status-icon
          class="demo-ruleForm"
          label-width="50px"
        >
          <el-form-item label="账户">
            <el-input
              type="text"
              v-model="form.username"
              :prefix-icon="User"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="form.type" placeholder="Select">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="密码">
            <el-input
              type="password"
              v-model="form.password"
              :prefix-icon="Lock"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="outerVisible = false">取消</el-button>
          <el-button type="primary" @click="addUser">新增</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped></style>
<script setup>
import { ref, reactive, computed, onMounted } from "vue"

import { ElMessageBox, ElMessage } from "element-plus"
import {
  Search,
  Edit,
  Check,
  Message,
  Star,
  Delete,
  ArrowLeftBold,
  ArrowRightBold,
  Refresh,
  Download,
  DocumentAdd,
  FolderAdd,
  Files,
  Right,
  ArrowDown,
  Plus,
} from "@element-plus/icons-vue"
import { useRouter, useRoute } from "vue-router"
import qs from "qs"
const tableData = ref([])
const loading = ref(false)

const outerVisible = ref(false)

const form = reactive({
  username: "",
  password: "",
  type: "GUEST",
})

const options = ref([
  {
    value: "ADMIN",
    label: "超级管理员",
  },
  {
    value: "MANAGER",
    label: "管理员",
  },
  {
    value: "GUEST",
    label: "普通用户",
  },
])

const username = ref("")

const usertype = ref("")

const circleUrl = ref(
  "https://image.windstormlab.com/img/ddb5987315caa3830a292164df0a02fb@478x476.jpg"
)

const router = useRouter()

const BASE_URL = import.meta.env.VITE_API_BASE_URL

const onLoad = () => {
  tableData.value = []
  loading.value = true
  fetch(`${BASE_URL}/user/queryList`, {
    method: "GET",
    mode: "cors",
    headers: {
      Token: localStorage.getItem("token"),
    },
    data: {
      page: 1,
      limit: 20,
    },
  })
    .then((response) => {
      return response.json()
    })
    .then((res) => {
      loading.value = false
      if (res.code == 0) {
        tableData.value = res.data.list
      } else {
        ElMessage({
          message: res.msg,
          type: "warning",
        })
      }
    })
    .catch((err) => {
      loading.value = false
      ElMessage({
        message: err,
        type: "warning",
      })
    })
}

const toPageSystem = () => {
  router.push({
    path: "/list",
  })
}

const changeUserAccess = (id, type, value) => {
  console.log(id, type, value)
  loading.value = true
  fetch(`${BASE_URL}/user/change`, {
    method: "POST",
    mode: "cors",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Token: localStorage.getItem("token"),
    },
    body: qs.stringify({
      id,
      type,
      value,
    }),
  })
    .then((response) => {
      return response.json()
    })
    .then((res) => {
      loading.value = false
      if (res.code == 0) {
        console.log(res.data)
        ElMessage({
          message: "权限修改成功",
          type: "success",
        })
      } else {
        ElMessage({
          message: res.msg,
          type: "warning",
        })
      }
    })
    .catch((err) => {
      loading.value = false
      ElMessage({
        message: err,
        type: "warning",
      })
    })
}

const inputValue = ref("")

const handleEdit = (index, row) => {
  const PASSWORD_REG =
    /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)]|[\(\)])+$)([^(0-9a-zA-Z)]|[\(\)]|[a-z]|[A-Z]|[0-9]){6,16}$/

  ElMessageBox.prompt("修改该用户密码", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    inputErrorMessage: "密码长度为6-16位",
    inputValue: inputValue.value,
    inputPlaceholder: "请输入密码",
    inputType: "password",
  })
    .then(({ value }) => {
      if (value !== "") {
        inputValue.value = value
        if (value.length >= 6 && value.length <= 16) {
          if (!PASSWORD_REG.test(value)) {
            ElMessage({
              message: "密码应包含字母、数字、特殊字符其中两种",
              type: "warning",
            })
            return
          } else {
            loading.value = true
            fetch(`${BASE_URL}/user/password`, {
              method: "POST",
              mode: "cors",
              headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                Token: localStorage.getItem("token"),
              },
              body: qs.stringify({
                id: row.id,
                password: value,
              }),
            })
              .then((response) => {
                return response.json()
              })
              .then((res) => {
                loading.value = false
                if (res.code == 0) {
                  inputValue.value = ""
                  onLoad()
                  ElMessage({
                    message: "修改成功",
                    type: "success",
                  })
                } else {
                  ElMessage({
                    message: res.msg,
                    type: "warning",
                  })
                }
              })
              .catch((error) => {
                ElMessage({
                  message: error,
                  type: "error",
                })
              })
          }
        } else {
          ElMessage({
            message: "密码长度为6-16位",
            type: "warning",
          })
          return
        }
      } else {
        ElMessage({
          message: "请输入内容",
          type: "warning",
        })
        return
      }
    })
    .catch(() => {})
}

const handleDelete = (index, row) => {
  ElMessageBox.confirm("是否确认删除该用户？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      loading.value = true
      fetch(`${BASE_URL}/user/delete`, {
        method: "POST",
        mode: "cors",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          Token: localStorage.getItem("token"),
        },
        body: qs.stringify({
          id: row.id,
        }),
      })
        .then((response) => {
          return response.json()
        })
        .then((res) => {
          loading.value = false
          if (res.code == 0) {
            onLoad()
            ElMessage({
              message: "删除成功",
              type: "success",
            })
          } else {
            ElMessage({
              message: res.msg,
              type: "warning",
            })
          }
        })
        .catch((error) => {
          ElMessage({
            message: error,
            type: "error",
          })
        })
    })
    .catch(() => {})
}

const addUser = () => {
  fetch(`${BASE_URL}/user/add`, {
    method: "POST",
    mode: "cors",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Token: localStorage.getItem("token"),
    },
    body: qs.stringify(form),
  })
    .then((response) => {
      return response.json()
    })
    .then((res) => {
      loading.value = false
      if (res.code == 0) {
        outerVisible.value = false
        onLoad()
        ElMessage({
          message: "新增成功",
          type: "success",
        })
      } else {
        ElMessage({
          message: res.msg,
          type: "warning",
        })
      }
    })
    .catch((error) => {
      ElMessage({
        message: error,
        type: "error",
      })
    })
}

const showAdd = () => {
  outerVisible.value = true
}

const logout = () => {
  ElMessageBox.confirm("确认退出后将清除登录记录", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      loading.value = true
      localStorage.removeItem("token")
      localStorage.removeItem("username")
      setTimeout(() => {
        loading.value = false
        router.replace({
          path: "/",
        })
      }, 1000)
    })
    .catch(() => {})
}

onMounted(() => {
  username.value = localStorage.getItem("username")
  usertype.value = localStorage.getItem("usertype")

  onLoad()
})
</script>
